﻿using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.Owin.Security;
using MVCForum.Mvc5.Identity.Models;
using mvcForum.Core.Interfaces.Services;
using System;
using System.Data.Entity;
using System.Net;
using System.Web;

namespace MVCForum.Mvc5.Identity.MvcForumIdentity {

	/// <summary>
	/// Class that handles logging in and out
	/// </summary>
	public class AuthenticationService : IAuthenticationService {
		private readonly DbContext context;

		public AuthenticationService(DbContext context) {
			this.context = context;
		}

		/// <summary>
		/// Sign in the account.
		/// </summary>
		/// <param name="account">The account to sign in</param>
		/// <param name="createPersistentCookie">Should the account be remembered on the site</param>
		public void SignIn(IAccount account, Boolean createPersistentCookie) {
			// Let's get the UserManager so we can "translate" the account to an ApplicationUser object.
			UserManager<ApplicationUser> manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(this.context));
			// Get the user matching the account.
			ApplicationUser user = manager.FindByName(account.AccountName);

			// Clear any cookies from third party providers.
			this.AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
			// Let's create an identity
			var identity = manager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);
			// Sign in, using Identity.
			this.AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = createPersistentCookie }, identity);
		}

		/// <summary>
		/// Sign out
		/// </summary>
		public void SignOut() {
			this.AuthenticationManager.SignOut();
		}

		private IAuthenticationManager AuthenticationManager {
			get {
				return HttpContext.Current.GetOwinContext().Authentication;
			}
		}
	}
}